import ReactCurrentOwner from './ReactCurrentOwner';
import { REACT_ELEMENT_TYPE } from '../shared/ReactSymbols';
function hasVaildRef(config) {
    return config.key !== void 0;
}
function hasVaildKey(config) {
    return config.key !== void 0;
}

const RESERVED_PROPS = {
    key: true,
    ref: true,
    __self: true,
    __source: true,
};
export function createElement(type, config, children) {
    let propName;
    const props = {};
    let key = null;
    let ref = null;
    let self = null;
    let source = null; // 定位创建源码的位置
    // 判断是否有配置文件
    if (config !== null) {
        if (hasVaildRef(config)) {
            ref = config.ref;
        }
        if (hasVaildKey(config)) {
            key = config.key;
        }
        self = config.__self === void 0 ? null : config.__self;
        source = config.__source === void 0 ? null : config.__souce;
        for (propName in config) {
            if (!RESERVED_PROPS.hasOwnProperty(propName)) {
                props[propName] = config[propName];
            }
        }
    }
    const childrenLength = arguments.length - 2;
    if (childrenLength === 1) {
        props.children = children;
    } else if (childrenLength > 1) {
        const childArray = Array(childrenLength);
        for (let i = 0; i < childrenLength; i++) {
            childArray[i] = arguments[i + 2];
        }
        props.children = childArray; //如果说是有多个儿子的话，props.children就是一个数组了
    }

    if (type && type.defaultProps) {
        const defaultProps = type.defaultProps;
        //只有当属性对象没有此属性对应的值的时候，默认属性才会生效，否则直接忽略
        for (propName in defaultProps) {
            if (props[propName] === undefined) {
                props[propName] = defaultProps[propName];
            }
        }
    }

    return ReactElement(
        type,
        key,
        ref,
        self,
        source,
        ReactCurrentOwner.current,
        props
    );
}

function ReactElement(type, key, ref, _self, _source, _owner, props) {
    // console.log(ReactCurrentOwner);
    const element = {
        $$typeof: REACT_ELEMENT_TYPE,
        type,
        key,
        ref,
        props,
        _owner,
        _self,
        _source,
    };
    // console.log(element);
    return element;
}
